Attachments

Upload a File to the File System

Description
In some circumstances, it is useful for an application to upload a file to the file system instead of into the database. Uploading a file into the database is a straightforward matter of using the File Upload display style of the Field Value code generation tag. However, a small code customization is needed to upload a file to the file system instead of to the database.
Variables
Upload Button Control
Select the upload button
Applies to
P_Upload Button Control class
Code
 
/// 
/// Click handler for Button that uploads a file to a Data subfolder which exists 
/// in the current application directory.
///     
public override void ${Upload Button Control}_Click(Object sender, EventArgs args)
{
    System.Web.UI.HtmlControls.HtmlInputFile inputFile;
    inputFile = ((System.Web.UI.HtmlControls.HtmlInputFile)(this.Page.FindControlRecursively("inputFile")));
	
    // If this code customization was added in Table Control Row, replace FindControlRecursively() with FindControl()
	// or comment out the above line of code and uncomment the line below
	// inputFile = ((System.Web.UI.HtmlControls.HtmlInputFile)(this.FindControl("inputFile")));
	
	
    if ((!(inputFile.PostedFile == null) && (inputFile.PostedFile.ContentLength > 0)))
    {
        // Get the name of the file to be uploaded and 
        // the location where the file needs to be saved.
        string fileName = System.IO.Path.GetFileName(inputFile.PostedFile.FileName);
        string saveLocation = (this.Page.Server.MapPath("..\\Data") + ("\\" + fileName));
        try 
        {
            // Save the file.
            inputFile.PostedFile.SaveAs(saveLocation);
            this.Page.Response.Write("The file has been uploaded.");
        }
        catch (Exception ex)
        {
            this.Page.Response.Write(("Error: " + ex.Message));
        }
    }
    else 
    {
        this.Page.Response.Write("Please select a file to upload.");
    }
}
  

Terms of Service Privacy Statement